package com.baseweb.webadmin.core.common;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderSupport;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * properties配置
 */
public class PropertiesConfig extends PropertiesLoaderSupport {
	
	private static String PROPERTIES_FILE_LOCATION_SEPARATING = ",; \t\n";
	
	private static Properties properties;
	
	static {
		new PropertiesConfig("classpath:config/config.properties,classpath:config/common.properties,classpath:config/jdbc.properties,classpath:config/mail.properties");
	}
	
	private PropertiesConfig(String resourceLocations){
		initProperties(resourceLocations);
	}
	
	protected void initProperties(String resourceLocations){
		String[] propertiesLocation = StringUtils.tokenizeToStringArray(resourceLocations, PROPERTIES_FILE_LOCATION_SEPARATING);
		
		Resource[] resources = new Resource[propertiesLocation.length];
		
		PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		
		for (int i = 0, size = propertiesLocation.length; i < size; i++){
			Resource resource = resourceResolver.getResource(StringUtils
					.trimWhitespace(propertiesLocation[i]));
			resources[i] = resource;
		}
		
		super.setIgnoreResourceNotFound(true);
		super.setLocalOverride(true);
		super.setFileEncoding("UTF-8");
		super.setLocations(resources);
		
		try {
			properties = this.mergeProperties();
		} catch (IOException e) {
			logger.warn("Could not load properties from "
					+ resourceLocations + ": " + e.getMessage());
		}
	}
	
	/**
	 * 读取String
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getProperty(String key, String defaultValue){
		String result;
		try{
			result = properties.getProperty(key, defaultValue);
		}catch (Exception ex){
			result = defaultValue;
		}
		return result;
	}
	
	/**
	 * 读取int
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static int getProperty(String key, int defaultValue){
		String value = properties.getProperty(key);
		int result;
		try{
			result = Integer.parseInt(value);
		}catch(Exception ex){
			result = defaultValue;
		}
		return result;
	}
	
	/**
	 * 读取boolean
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static boolean getProperty(String key, boolean defaultValue){
		String value = properties.getProperty(key);
		boolean result;
		try{
			result = Boolean.parseBoolean(value);
		}catch(Exception ex){
			result = defaultValue;
		}
		
		return result;
	}
}
